/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.google.code.japidiff;

import java.util.Set;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.LinkedList;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Writer;
import java.io.OutputStreamWriter;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.project.MavenProject;
import org.objectweb.asm.ClassReader;
import name.fraser.neil.plaintext.diff_match_patch;

/**
 * Check two jars API
 *
 * @version $Revision: $
 * @goal diff
 * @phase package
 * @requiresDependencyResolution test
 * @execute phase="package"
 * @inheritByDefault true
 * @description Check two jars API
 */
public class Mojo extends AbstractMojo {

    /**
     * The maven project.
     *
     * @parameter expression="${project}"
     * @required
     * @readonly
     */
    private MavenProject project;

    /**
     * Name of the generated JAR.
     *
     * @parameter alias="jarName" expression="${jar.finalName}" default-value="${project.build.directory}/${project.build.finalName}.jar"
     * @required
     */
    private String finalName;

    /**
     * The jar to check against
     *
     * @parameter
     */
    private String jar;

    /**
     * Check only public apis
     *
     * @parameter default-value="true"
     */
    private boolean publicApis;

    /**
     * The filter used for classes
     *
     * @parameter
     */
    private String filter;

    /**
     * @parameter expression="${project.build.directory}/japidiff"
     */
    private File outputDir;

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            String api1 = createApi(finalName);
            String api2 = createApi(getDependency(jar).getFile().toString());
            if (!api1.equals(api2)) {
                diff_match_patch diff =new diff_match_patch();
                LinkedList diffs = diff.diff_main(api1, api2);
                String delta = diff.diff_toDelta(diffs);
                //this.getLog().error(diffs.toString());
                this.getLog().error(delta);
                throw new MojoFailureException("APIs different");
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Unable to generate api summary", e);
        }
    }

    private Artifact getDependency(String jar) {
        String[] p = jar.split(":");
        for (Artifact a : (Set<Artifact>) project.getDependencyArtifacts()) {
            if (a.getGroupId().equals(p[0]) && a.getArtifactId().equals(p[1]) && a.getVersion().equals(p[2])) {
                return a;
            }
        }
        throw new IllegalStateException("Can not find a dependency for: " + jar);
    }

    public String createApi(String jar) throws IOException {
        Collection<JavaClass> classes = read(jar);
        Printer printer = new Printer();
        printer.publicApis = publicApis;
        printer.classNames = filter;
        StringBuilder builder = new StringBuilder();
        printer.printClasses(classes, builder);
        String str = builder.toString();
        try {
            outputDir.mkdirs();
            File output = new File(outputDir, new File(jar).getName() + ".txt");
            Writer w = new OutputStreamWriter(new FileOutputStream(output));
            w.write(str);
            w.close();
        } catch (IOException e) {
            getLog().warn("Error writing api to file", e);
        }
        return str;
    }

    public Collection<JavaClass> read(String jar) throws IOException {
        getLog().debug("Reading api from " + jar);
        JavaClassBuilder v = new JavaClassBuilder();
        ZipFile f = new ZipFile(jar);
        Enumeration<? extends ZipEntry> en = f.entries();
        while (en.hasMoreElements()) {
            ZipEntry e = en.nextElement();
            String name = e.getName();
            if (name.endsWith(".class")) {
                ClassReader cr = new ClassReader(f.getInputStream(e));
                cr.accept(v, 0);
            }
        }
        return v.getClasses();
    }

}
